package com.copa.ums.modules.ums.controller;

import com.copa.ums.common.api.CommonPage;
import com.copa.ums.common.vo.ResponseVo;
import com.copa.ums.modules.ums.model.UmsResource;
import com.copa.ums.modules.ums.service.UmsResourceService;
import com.copa.ums.security.component.DynamicSecurityMetadataSource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author copa
 * @since 2022-10-31
 */
@RestController
@Api(tags = "资源管理")
@Tag(name = "资源管理", description = "资源管理")
@RequestMapping("resource")
public class UmsResourceController {

    @Resource
    private UmsResourceService resourceService;

    /**
     * 为了避免循环依赖，所以写到这里了
     */
    @Resource
    private DynamicSecurityMetadataSource dynamicSecurityMetadataSource;

    @ApiOperation("添加后台资源")
    @PostMapping("create")
    public ResponseVo<String> create(@RequestBody UmsResource resource) {
        dynamicSecurityMetadataSource.clearDataSource();
        return resourceService.create(resource);
    }

    @ApiOperation("修改后台资源")
    @PostMapping("update/{resourceId}")
    public ResponseVo<String> update(@PathVariable("resourceId") Long resourceId,
                                     @RequestBody UmsResource resource) {
        dynamicSecurityMetadataSource.clearDataSource();
        return resourceService.update(resourceId, resource);
    }

    @ApiOperation("根据id获取资源详情")
    @GetMapping("{resourceId}")
    public ResponseVo<UmsResource> getItem(@PathVariable("resourceId") Long resourceId) {
        return ResponseVo.success(resourceService.getById(resourceId));
    }

    @ApiOperation("根据ID删除后台资源")
    @PostMapping("delete/{resourceId}")
    public ResponseVo<String> delete(@PathVariable("resourceId") Long resourceId) {
        dynamicSecurityMetadataSource.clearDataSource();
        return resourceService.delete(resourceId);
    }

    @ApiOperation("分页模糊查询后台资源")
    @GetMapping("list")
    public ResponseVo<CommonPage<UmsResource>> list(@RequestParam(value = "categoryId", required = false) Long categoryId,
                                                    @RequestParam(value = "nameKeyword", required = false) String nameKeyword,
                                                    @RequestParam(value = "urlKeyword", required = false) String urlKeyword,
                                                    @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        return resourceService.list(categoryId, nameKeyword, urlKeyword, pageSize, pageNum);
    }

    @ApiOperation("查询所有后台资源")
    @GetMapping(value = "listAll")
    public ResponseVo<List<UmsResource>> listAll() {
        return ResponseVo.success(resourceService.list());
    }
}

